#只做字典替换功能
import  re,os,sys
def read_file(filename):
   with open(filename,'r',encoding='utf-8') as r:
       lines=r.readlines()
   return lines
def load_dic(filename):
    dic={}
    lines=read_file(filename)
    for line in lines:
        try:
            k=line.split('\t')[0].lower().strip()
            v=line.split('\t')[1].strip()
            if k not in dic:
                dic[k]=v
        except:
            print('【Erro】 {}单词与音标之间需以tab键隔开'.format(line))
    return dic
def mkdir(dst):
    if not os.path.exists(dst):
        os.makedirs(dst)
def get_words(filename,old_dic,errodic):
    _,file=os.path.split(filename)
    lines=read_file(filename)
    new_lines_list = []  # 新的所有句子转换结果
    for i in range(0,len(lines),2):
        split_sentence=lines[i].strip().split('\t')
        sequnece=split_sentence[0] #序号
        newsentence=[]
        # newsentence=split_sentence[1]#以空白符分割开后以空格连接
        # sentence = re.sub('[^a-z\u00C0-\u00FF\s]', '', newsentence.lower())
        new_line = []#新的一行
        words_list=re.split('\s+',split_sentence[1])
        syllable_list=re.split('/',lines[i+1].strip())
        #词典中的词替换
        if len(words_list)==len(syllable_list):
            for j in range(len(words_list)):
                word=re.sub('[^a-zA-Z\u00C0-\u00FF\s]','',words_list[j]).lower().strip()
                if word in old_dic:
                    new_line.append(old_dic[word].strip())
                    newsentence.append('*'+words_list[j])
                else:
                    new_line.append(syllable_list[j].strip())
                    newsentence.append(words_list[j])
        else:
            new_line=[word.strip() for word in syllable_list]
            if file not in errodic:
                errodic[file]=[sequnece+'\t'+' '.join(newsentence)+'\n'+'\t'+' / '.join(new_line)+'\n']
            else:
                errodic[file].append(sequnece+'\t'+' '.join(newsentence)+'\n'+'\t'+' / '.join(new_line)+'\n')
        new_lines_list.append(sequnece+'\t'+' '.join(newsentence)+'\n'+'\t'+' / '.join(new_line)+'\n')
    return new_lines_list

def main():
    if len(sys.argv) < 3:
        print(sys.stderr, "usage: python 词典替换.py in_path out_path")
        exit()
    else:
        # filename=r'2-7-8.txt'
        # out_file = '11.txt'
        path = sys.argv[1]
        out = sys.argv[2]
        dic_filename = '勿删/德语词典.txt'
        # path = input('输入路径：')
        # out = input('输出路径：')
        errodic = {}
        for rt, _, files in os.walk(path):
            for file in files:
                try:
                    filename = os.path.join(rt, file)
                    alter_filename = file
                    old_dic = load_dic(dic_filename)
                    new_lines_list = get_words(filename, old_dic, errodic)
                    with open(os.path.join(out, alter_filename), 'w', encoding='utf-8') as w:
                        w.write(''.join(new_lines_list))
                except Exception as e:
                    if file not in errodic:
                        errodic[file] = [str(e)]
                    else:
                        errodic[file].append(str(e))
        if errodic != {}:
            with open(os.path.join('词典替换错误.txt'), 'w', encoding='utf-8') as w:
                w.write('文本与音标长度不一致\n')
                for k, v in errodic.items():
                    w.write('*' * 20 + k + '*' * 20 + '\n')
                    w.write(''.join(v))
main()
# 词典去重
# old_dic = load_dic('词典-已校对.txt')
# lines=read_file('总.txt')
# for line in lines:
#     word=re.sub('[^a-zA-Z\u00C0-\u00FF\s]','',line).lower().strip()
#     if word in old_dic:
#         print(word,line)
#     else:
#         with open('去重后.txt','a',encoding='utf-8') as w:
#             w.write(line)